package proxy

import (
	"errors"
	"sync/atomic"

	"gitee.com/fanshuaiself/sidecar/util"
)

type ProxyPlugin struct {
	discovery *discovery
	forwarding forwarding

	running int32 
	closeFn func()	
}

func (p *ProxyPlugin) Initialize(config *util.Config, closeFunc func()) {
	p.discovery = newDiscovery()
	if config.UseFasthttp {
		p.forwarding = newGinForwarding()
	} else {
		p.forwarding = newFasthttpForwarding()
	}
	p.closeFn = closeFunc
}

func (p *ProxyPlugin) Start() error {
	if !atomic.CompareAndSwapInt32(&p.running, 0, 1) {
		return errors.New("ProxyPlugin has started")
	}

	p.discovery.Start()
	p.forwarding.Forwarding()
	return nil
}

func (p *ProxyPlugin) Stop () {
	p.running = 0
	p.discovery.Stop()
	p.forwarding.DoStop()
}